package command;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;

import camel_underscore_eclipse_plugin.Activator;
import converter.ConverterCamelUnderscore;


public class ConvertToCamelCaseHandler extends AbstractHandler implements IHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		try {
			//get editor
			IEditorPart editorPart = Activator.getDefault().getWorkbench()
					.getActiveWorkbenchWindow().getActivePage()
					.getActiveEditor(); 
			
			if (editorPart instanceof ITextEditor){
				ITextEditor textEditor=(ITextEditor)editorPart;
				IDocumentProvider provider=textEditor.getDocumentProvider();
				IDocument doc=provider.getDocument(textEditor.getEditorInput());
				ISelection selection=textEditor.getSelectionProvider().getSelection();
				if (selection instanceof TextSelection){
					if (!selection.isEmpty()) {
						TextSelection textSelection = (TextSelection) selection;
						StringBuilder text = new StringBuilder();
						text.append(textSelection.getText());
						ConverterCamelUnderscore converter = new ConverterCamelUnderscore();
						String newText = converter.toCamelCase(text);
						int offset = textSelection.getOffset();
						int length = textSelection.getLength();
						doc.replace(offset, length, newText);
						length = newText.length();
						textEditor.selectAndReveal(offset, length);//select text programmatically
					}
				}
			}
		} catch (Exception e) {	
			Logger logger = Logger.getAnonymousLogger();
			logger.log(Level.SEVERE, "an exception was thrown", e);
		}
		return null;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	@Override
	public boolean isHandled() {
		return true;
	}

}
